
//#ifdef H5
var device_type = 'h5'
//#endif

//#ifdef APP-PLUS
var device_type = 'app'
//#endif

//#ifdef MP
var device_type = 'wxapp'
//#endif

var app = getApp();

var host = ''

module.exports = {
	HOST: host,
	API_ROOT: host + '/api',
	DeviceType: device_type,
	post(options) {
		this.request(options);
	},
	delete(options) {
		options.method = 'DELETE';
		this.request(options);
	},
	get(options) {
		options.method = 'GET';
		this.request(options);
	},
	put(options) {
		options.method = 'PUT';
		this.request(options);
	},
	request(options) {
		var apiRoot = this.API_ROOT;
		var token = '';
		var clientid = '';
		var terminal = 'app';
		// #ifndef H5
			terminal = 'h5';
		// #endif
		if(uni.getStorageSync('userInfo')){
			token = uni.getStorageSync('userInfo').token
		}
		uni.request({
			url: apiRoot + options.url,
			data: options.data,
			method: options.method ? options.method : 'POST',
			header: {
				'Content-Type': 'application/json',
				'Access-Token': token,
				'platform':clientid
			},
			success: res => {
				console.log(res)
				var data = res.data;
				if(data.code==301){
					uni.reLaunch({
						url:'/pages/login/login'
					})
					return;
				}
				if(data.code==500){
					uni.showToast({
						title:data.message,icon:"none"
					})
					return;
				}
				let routes = getCurrentPages();
				let curRoute = routes[routes.length - 1].route
				
				if(data.status === 0){
					uni.showToast({
						title:data.message,icon:"none"
					})
					return;
				}
				options.success(data.data);
			},
			fail: function(res) {
				console.log(res)
				if (options.fail) {
					options.fail(res)
				}
			},
			complete: options.complete ? options.complete : null
		});
	},
	uploadFile(options) {

		options.url = this.API_ROOT + options.url;

		var token = '';
		var openid = '';
		let that = this;
		let oldSuccess = options.success;
		options.success = function(res) {
			let data = JSON.parse(res.data);
			if(data.status == 1){
				oldSuccess(data);
			}else{
				uni.showToast({
					title:data.message,icon:'none'
				})
				return;
			}

		}
		if(uni.getStorageSync('userInfo')){
			token = uni.getStorageSync('userInfo').token
		}
		options.header = {
			'Access-Token': token,
			'platform': device_type
		};
		uni.uploadFile(options);

	},
	getToken() {
		var token = '';
		try {
			token = uni.getStorageSync('token')
		} catch (e) {
			// Do something when catch error
		}

		return token;
	}
};
